<?php
/**
 *
 * @property Admin_menu_mdl $menu
 * @property Admin_role_mdl $role
 */
class Admin_mdl extends MY_Model{

	 protected $_table = parent::T_M_ADMIN;

	 protected $_cacheTime = 604800;//7天
	 protected $_cookieKey = 'adminauth';
	 /**
	  * 超级管理员角色ID
	  * @var int
	  */
	 const SUPER_ROLE_ID = 1;

	public function __construct(){
		parent::__construct();
		$this->load->database('default');
	}
	/**
	 * 登录
	 * @param unknown_type $username
	 * @param unknown_type $password
	 * @return boolean|unknown
	 */
	public function login($username,$password){
		$admin = $this->db->select('*')
					->from($this->_table)
					->where('username',$username)
					->limit(1)
					->get()
					->row_array();
		if( empty($admin) || $admin['password']!=md5($password) ){
			return FALSE;
		}
		$this->afterLogin($admin);
		return $admin;
	}
	/**
	 * 登录后操作
	 * @param unknown_type $admin
	 */
	public function afterLogin($admin){
		if( ! isset($_SESSION) ){
			session_start();
		}
		$_SESSION['admin'] = $admin;
		$loginTime = time();
		$ip = sprintf("%u",ip2long( $this->input->ip_address() ));

		$update['loginTime'] = $loginTime;
		$update['loginIP'] = $ip;

		return $this->db->where('id',$admin['id'])->update($this->_table,$update);
	}
	public function getAdminList(){
		$list = $this->db->select('id,username')->get($this->_table)->result_array();
		return array_combine(array_column($list, 'id'), $list);
	}
	/**
	 * 获取当前登录用户
	 * @return boolean|unknown
	 */
	public function getUser(){
		if( ! isset($_SESSION) ){
			session_start();
		}
		if( empty($_SESSION['admin']) || empty($_SESSION['admin']['id']) ){
			return FALSE;
		}
		return $_SESSION['admin'];
	}
	/**
	 * 登出
	 * @return boolean
	 */
	public function logout(){
		if( ! isset($_SESSION) ){
			session_start();
		}
		if( empty($_SESSION['admin']) || empty($_SESSION['admin']['id']) ){
			return FALSE;
		}
		$_SESSION['admin'] = NULL;
		session_destroy();
		return TRUE;
	}
	/**
	 * 获取管理员有权限且可见的栏目列表
	 */
	public function getVisibleMenuList($adminID,$select='*'){
		$this->load->model('Admin_menu_mdl','menu');
		$this->load->model('Admin_role_mdl','role');
		// 获取全部可见栏目
		$where = array('isVisible'=>1);
		$allMenuList = $this->menu->getMenuList($select,$where);
		// 获取该用户的角色ID列表
		$roleIdList  = $this->getRoleIdListByAdminID($adminID);
		// 验证该用户是否超级管理员
		$isSuperManager = $this->isSuperManager($adminID,$roleIdList);
		// 如果为超级管理员:直接返回全部列表
		if( $isSuperManager ){
			return $allMenuList;
		}
		// 如果不是,获取该用户的角色ID所映射的栏目ID列表
		$menuIdList = $this->role->getMenuIdListOfRole($roleIdList);
		$allMenuList = array_combine(array_column($allMenuList, 'id'), $allMenuList);
// 		pr($allMenuList);
		// 获取所有有权限的栏目及其上级栏目
		$menuList = array();// 存储已找到的所有栏目
		while( ! empty($menuIdList) ){
			$menuID = array_shift($menuIdList);
			if ( isset( $allMenuList[$menuID] ) ){
				$menuList[$menuID] = $allMenuList[$menuID];
				if( ! array_key_exists($allMenuList[$menuID]['parentID'], $menuList) ){
					array_push($menuIdList, $allMenuList[$menuID]['parentID']);
				}
			}
		}
		return $menuList;
	}
	/**
	 * 检测是否有对该链接操作的权限
	 * @param string $link
	 */
	public function checkLink($adminID,$link){
		$access = (bool)$this->db->select('*')
							->where('uid',$adminID)
							->where('link',$link)
							->from(parent::V_M_ADMIN_MENU)
							->limit(1)
							->get()
							->num_rows();
		if( ! $access ){
			$access = (bool)$this->db->select('*')
								->from(parent::T_M_ADMIN_ROLE)
								->where('uid',$adminID)
								->where('rid',self::SUPER_ROLE_ID)
								->limit(1)
								->get()
								->num_rows();
		}
		return $access;
	}
	/**
	 * 判断是否超级管理员($adminID,$roleIdList必须传一个)
	 * @param int 	$adminID		管理员ID
	 * @param array $roleIdList		角色ID列表
	 * @return boolean
	 */
	public function isSuperManager($adminID=NULL,$roleIdList=array()){
		if( !empty($roleIdList) ){
			return in_array(self::SUPER_ROLE_ID, $roleIdList);
		}
		if( empty($adminID) ) return FALSE;
		$query = $this->db->select('*')->from(parent::T_M_ADMIN_ROLE)
						->where('rid',self::SUPER_ROLE_ID)
						->where('uid',$adminID)
						->limit(1)
						->get();
		return (bool)$query->num_rows();
	}
	/**
	 * 为管理员增加角色
	 * @param int $adminID
	 * @param array $roleIdList
	 */
	public function addRole2Admin($adminID,$roleIdList){
		$map = array();
		foreach ($roleIdList as $roleId){
			$map[] = array(
					'uid'=>$adminID,
					'rid'=>$roleId,
			);
		}
		return $this->db->insert_batch(parent::T_M_ADMIN_ROLE,$map);
	}
	/**
	 * 为管理员删除角色
	 * @param int $adminID
	 * @param array $roleIdList
	 */
	public function deleteRole2Admin($adminID,$roleIdList){
		return $this->db->where('uid',$adminID)
						->where_in('rid',$roleIdList)
						->delete(parent::T_M_ADMIN_ROLE);
	}
	/**
	 * 删除一个管理员
	 * @param int $adminID
	 */
	public function deleteAdmin($adminID){
		// 删除管理员表
		$res = $this->db->where('id',$adminID)->delete($this->_table);
		// 删除管理员_角色表
		if( $res ){
			$this->db->where('uid',$adminID)->delete(parent::T_M_ADMIN_ROLE);
		}
		return $res;
	}

	/**
	 * 获取管理员与角色的映射关系列表
	 */
	public function getAdminRoleMap(){
		return $this->db->get(parent::T_M_ADMIN_ROLE)->result_array();
	}
	/**
	 * 通过管理员ID获取角色ID列表
	 * @param int $adminID
	 */
	public function getRoleIdListByAdminID($adminID){
		$roleIdList = $this->db->select('rid')
							->where('uid',(int)$adminID)
							->get(parent::T_M_ADMIN_ROLE)
							->result_array();
		return array_column($roleIdList, 'rid');
	}
	/**
	 * 检测用户名是否存在
	 * @param string $username
	 * @param int $adminID [可选]不检测的用户ID
	 * @return boolean
	 */
	public function checkUsernameIsExists( $username , $adminID = NULL ){
		$username = trim($username);
		if( !empty($adminID) ){
			$this->db->where('id !=',$adminID);
		}

		$query = $this->db->select('username')
					->from($this->_table)
					->where('username',$username)
					->limit(1)
					->get();
		return (bool)$query->num_rows() > 0 ;

	}
}
